# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>

import logging
import os
from excavator.utils.shell import c_run_cmd
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.efi import EfiInfoModel, X86_64_EFI_SHIM, AARCH64_EFI_SHIM, OPENCLOUD_EFIDIR_CANONICAL_PATH
from excavator.models.report import notify_err, notify_info
from excavator.group import HarvestsGroup

logger = logging.getLogger("excavator.job")


class HarvestsEfi(Job):
    group = HarvestsGroup
    requires = ()
    provides = (EfiInfoModel,)

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "harvests efi")
        logger.info("harvests efi")
        if not self.is_efi():
            EfiInfoModel.create(is_efi=False)
            msg = "bios system"
            logger.info(msg)
            notify_info(msg, self.name)
            return

        logger.info("get system arch")
        cmd = "/usr/bin/uname -m "
        rc, ro = c_run_cmd(cmd)
        if rc != 0:
            EfiInfoModel.create(is_efi=True)
            logger.warning("get system arch {}".format(ro))
            notify_err("get system arch {}".format(ro), self.name)
            return
        arch = ro.strip()
        if arch == "x86_64":
            shim_path = os.path.join(OPENCLOUD_EFIDIR_CANONICAL_PATH, X86_64_EFI_SHIM)
        elif arch == "aarch64":
            shim_path = os.path.join(OPENCLOUD_EFIDIR_CANONICAL_PATH, AARCH64_EFI_SHIM)
        else:
            EfiInfoModel.create(is_efi=True)
            msg = "unsupport system arch"
            logger.warning(msg)
            notify_err(msg, self.name)
            return
        if not os.path.exists(shim_path):
            msg = "can't find shim {}".format(shim_path)
            logger.warning(msg)
            notify_err(msg, self.name)
            return
        shim_bak_path = "{}_bak".format(shim_path)
        EfiInfoModel.create(is_efi=True, shim_path=shim_path, shim_bak_path=shim_bak_path)
        msg = "get efi info success"
        logger.info(msg)
        notify_info(msg, self.name)
        if self.is_secure_boot():
            msg = "unsupport secureboot efi, please disabled it and upgrade."
            logger.warning(msg)
            notify_err(msg, self.name)

    @staticmethod
    def is_efi():
        return os.path.exists("/sys/firmware/efi")

    def is_secure_boot(self):
        if not self.is_efi():
            return False
        cmd = "mokutil --sb-state"
        rc, ro = c_run_cmd(cmd)
        if rc != 0:
            return False
        if "disabled" in ro:
            return False
        return True
